package com.leo.util;

import java.util.Date;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

/**
 * 使用memcached的缓存实用类.
 * 
 * @author
 * 
 */
public class MemcachedUtil {
	// 创建全局的唯一实例
	protected static MemCachedClient mcc = new MemCachedClient();

	public static MemCachedClient getMcc() {
		return mcc;
	}

	protected static MemcachedUtil memCached = new MemcachedUtil();

	// 设置与缓存服务器的连接池
	static {
		//设置logger level
		com.danga.MemCached.Logger.getLogger(
				"com.danga.MemCached.MemCachedClient").setLevel(
				com.danga.MemCached.Logger.LEVEL_ERROR);

		// 服务器列表和其权重
		String[] servers = {"127.0.0.1:11211" }; // 这里开了1个，memcache会自动负载均衡
		Integer[] weights = { 3 };// 设置存储权重，数据会优先存储到权重大的一个服务器

		// 获取socke连接池的实例对象
		SockIOPool pool = SockIOPool.getInstance();

		// 设置服务器信息
		pool.setServers(servers);
		pool.setWeights(weights);

		// 设置初始连接数、最小和最大连接数以及最大处理时间
		pool.setInitConn(5);
		pool.setMinConn(5);
		pool.setMaxConn(250);
		pool.setMaxIdle(1000 * 60 * 60 * 6);

		// 设置主线程的睡眠时间
		pool.setMaintSleep(30);

		// 设置TCP的参数，连接超时等
		pool.setNagle(false);
		pool.setSocketTO(3000);
		pool.setSocketConnectTO(0);

		// 初始化连接池
		pool.initialize();

		// 压缩设置，超过指定大小（单位为K）的数据都会被压缩
		mcc.setCompressEnable(true);
		mcc.setCompressThreshold(64 * 1024);
	}

	/**
	 * 保护型构造方法，不允许实例化！
	 * 
	 */
	protected MemcachedUtil() {

	}

	/**
	 * 获取连接（单例）
	 * 
	 */
	public static MemcachedUtil getInstance() {
		return memCached;
	}

	public boolean add(String key, Object value) {
		return mcc.add(key, value);
	}

	public boolean add(String key, Object value, Date expiry) {
		return mcc.add(key, value, expiry);
	}
	
	public boolean add(String key, Object value, long seconds) {
		return mcc.add(key, value, new Date(new Date().getTime() + 1000*seconds ) );
	}

	public boolean replace(String key, Object value) {
		return mcc.replace(key, value);
	}

	public boolean replace(String key, Object value, Date expiry) {
		return mcc.replace(key, value, expiry);
	}

	public boolean delete(String key, Date expiry) {
		return mcc.delete(key,expiry);
	}
	
	public boolean delete(String key) {
		return mcc.delete(key);
	}

	/**
	 * 根据指定的关键字获取对象.
	 * 
	 * @param key
	 * @return
	 */
	public Object get(String key) {
		return mcc.get(key);
	}

/*	public static void main(String[] args) {
		MemcachedUtil cache = MemcachedUtil.getInstance();
		Date date = new Date();
		Long start = System.currentTimeMillis();

		int cnt = 0;
		int sum = 1000;
		for (int i = 1; i <= sum; i++) { // 插入*万条数据
			if (cache.add("abc" + i, "hello" + i)) // 添加数据并统计
				cnt++;
		}

		Long end = System.currentTimeMillis();
		System.err.printf("共耗时： %s毫秒，插入%d/%d条\n",""+(end - start), cnt, sum);
	}*/
	public static void main(String[] args) {
		MemcachedUtil cache = MemcachedUtil.getInstance();
		//System.out.println(cache.add("key", "value", new Date( new Date().getTime() + 1000*10)) );
		Object x = cache.get(null);
		x = cache.get("123");
		int sc = 0;
		while(true){
			 try {
				Thread.sleep(1000);
				System.out.printf("%ds:%s\n", ++sc ,  cache.get("key") );
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		}
		
	}
}
